package com.yutel.gps.http;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yutel.gps.model.LocationsNode;
import com.yutel.gps.model.RunParameter;
import com.yutel.gps.server.Gps;

public class BaiduGps implements Gps {
	private final Logger log = LoggerFactory.getLogger(BaiduGps.class);
	private static String url = "http://api.map.baidu.com/ag/coord/convert";

	@Override
	public LocationsNode convert(LocationsNode ln) {
		try {
			StringBuilder sb = new StringBuilder();
			sb.append(url);
			sb.append("?from=0&to=4");
			sb.append("&x=").append(ln.getSrcLng().trim());
			sb.append("&y=").append(ln.getSrcLat().trim());
			String res = ReportClient.getIns().get(sb.toString());
			if (res == null) {
				return null;
			}
			JSONObject json = new JSONObject(res);
			if (0 != json.getInt("error")) {
				log.error("[{},{}]:{}", ln.getSrcLng(), ln.getSrcLat(), res);
				return null;
			}
			byte[] lng = Base64.decodeBase64(json.getString("x"));
			byte[] lat = Base64.decodeBase64(json.getString("y"));
			ln.setAimLng(new String(lng));
			ln.setAimLat(new String(lat));
			ln.setStatus(RunParameter.getIns().getSuccessValue());
			return ln;
		} catch (Exception e) {
			log.error("convert", e);
			return null;
		}
	}
}
